<template xmlns="">
  <div class="registerInfo-container">
    <modules-title title-name="入库">
      <template slot="btn">
        <el-button type="primary" @click="tosSorageLog">入库日志</el-button>
        <el-button type="primary" class="main-btn" @click="save">保存</el-button>
      </template>
    </modules-title>
    <div class="main">
      <div class="searchBar">
        <el-form inline :model="storage">
          <!--          <el-form-item label="入库日期">-->
          <!--            <el-date-picker-->
          <!--              class="searchBar_picker"-->
          <!--              v-model="storage.date"-->
          <!--              value-format="yyyy-MM-dd"-->
          <!--              type="date"-->
          <!--              @change="onDate"-->
          <!--              :picker-options="pickerOptions"-->
          <!--              placeholder="入库日期">-->
          <!--            </el-date-picker>-->
          <!--          </el-form-item>-->
          <el-form-item label="供应商">
            <el-input
              class="searchBar_input"
              placeholder="供应商"
              v-model="storage.manufacturers">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="table">
        <el-form :model="formData" ref="formData" :rules="rules" class="demo-ruleForm">
          <el-table
            :data="formData.tableData"
            max-height="750"
            :header-cell-style="{backgroundColor: '#F5F5F5',color: '#333333',fontFamily: 'MicrosoftYaHeiUI',fontSize: '14px',fontWeight: 900,}">
            <el-table-column type="index">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  {{scope.$index + 1}}
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="药品名称" class="cell_1" width="180">
              <template slot-scope="scope">
                <el-form-item class="item_form"
                              :prop="'tableData.'+scope.$index+'.product_name'"
                              :rules="rules.tableDataP_name"
                >
                  <el-autocomplete
                    class="table_input_n"
                    v-model="scope.row.product_name"
                    :fetch-suggestions="querySearch"
                    placeholder="药品关键字"
                    :trigger-on-focus="false"
                    :popper-append-to-body="false"
                    @focus="focusInp(scope.$index)"
                    @change="(item)=>{onChangeInp(scope.$index,item)}"
                    @clear="clearSl(scope.$index)"
                    @select="(item)=>{handleSelect(scope.$index,item)}">
                    <template slot-scope="{ item }">
                      <div class="product-item">
                        <div class="name">
                          <span>{{ item.product_name }}</span
                          ><span>({{ item.pack }})</span>
                          <span>({{ item.production }})</span>
                        </div>
                      </div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="规格" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  {{scope.row.specifications}}
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="厂家" align="center" width="280">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  {{scope.row.production}}
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="190" >
              <template slot="header" slot-scope="scope" >
                <span style="color: red">*</span><span>入库数量</span>
              </template>
              <template slot-scope="scope">
                <el-form-item class="item_form"
                              :prop="'tableData.'+scope.$index+'.number'"
                              :rules="rules.tableDataN"
                >

                  <el-input v-model.number="scope.row.number" @blur="blurNn(scope.$index)" :ref="'numIn' + scope.$index"
                            class="table_input1">
                  </el-input>
                  <el-select v-model="scope.row.unit" @change="onChangeUn(scope.$index,scope.row.unit)"
                             class="table_select1" placeholder="">
                    <el-option
                      v-for="item in scope.row.unitList"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="进货价" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form"
                              :prop="'tableData.'+scope.$index+'.buy_price'"
                              :rules="rules.tableDataB"
                >
                  <el-input v-model="scope.row.buy_price" @blur="blurBu(scope.$index)" class="table_input">
                    <template slot="append"><span v-if="scope.row.unit">元/</span>{{scope.row.unit}}
                    </template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="处方价" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form"
                              :prop="'tableData.'+scope.$index+'.price'"
                              :rules="rules.tableDataP"
                >
                  <el-input v-model="scope.row.price" @blur="blurPr(scope.$index)" class="table_input">
                    <template slot="append"><span v-if="scope.row.piece_unit">元/</span>{{scope.row.piece_unit}}
                    </template>
                  </el-input>

                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address3" label="批号" v-if="state.drugs_management.function_set" align="center">
              <template #default="{row}">
                <el-form-item class="item_form">
                  <el-input v-model="row.batch_no" class="table_input_p"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="有效期" width="200" align="center">
              <template slot-scope="scope">
                <el-form-item class="item_form">
                  <div class="box_input">
                    <div class="box_select">

                      <el-select v-model="scope.row.obj.li" class="table_select"
                                 @change="onchange(scope.$index,scope.row.obj.li)" placeholder="年">
                        <el-option
                          v-for="item in scope.row.obj.list"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
                      <el-date-picker
                        class="table_picker"
                        v-model="scope.row.expire_time"
                        :picker-options="pickerOptions"
                        @change="onchangeEx(scope.$index,scope.row.expire_time)"
                        value-format="yyyy-MM-dd"
                        type="date">
                      </el-date-picker>
                    </div>
                    <i class="el-icon-delete delete" @click="deleteDrug(scope.$index)"></i>

                  </div>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>


        <div>
          <el-button @click="addDrug" type="text">添加药品</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      class="dialog"
      title="系统提示"
      :visible.sync="dialogVisible"
      width="24%"
      :close-on-click-modal="false">
      <div class="div_title">是否确定保存?</div>
      <span slot="footer" class="dialog-footer">
          <el-button class="border-btn" @click="dialogVisible = false">取 消</el-button>
          <el-button class="main-btn" type="primary" :disabled="booleBu" @click="determine">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
  import {addStoragerList, getDrugsList, getCentralList, getDefault} from '@/api/drugsManagement';
  import {moneyFormat} from "@/filters/index"

  export default {
    name: 'pushWarehouse',
    data() {
      var checkSe = (rule, value, callback) => {
        //debugger
        let that = this
        if (value === '' || value === null) {
          callback(new Error('请输入药品'));
        } else if (that.inputList.length === 0) {
          callback(new Error('该药品没有被录入'));
        } else {
          callback();
        }
      };
      var checkNu = (rule, value, callback) => {
        var reg = /(^[1-9]\d*$)/
        if (value === '' || value === null) {
          callback(new Error('请输入数量'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入正确数量'));
        } else if (value > 999999) {
          callback(new Error('入库数量最大值9999'));
        } else {
          callback();
        }
      };
      var checkbP = (rule, value, callback) => {
        var reg = /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$|0$|0.00$/
        if (value === '' || value === null) {
          callback(new Error('请输入数量'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入正确数量'));
        } else {
          callback();
        }
      };
      return {
        booleP_n: false,
        date: '',
        dialogVisible: false,
        storage: {//入库
          date: '',
          supply: '1',
          manufacturers: ''
        },
        formData: {
          tableData: [
            {
              product_id: 0,//id
              buy_price: null,//进货价
              price: null,//处方价
              number: null,//数量
              batch_no: "",//批次号
              expire_time: "",//有效期
              production: "厂家",//厂家
              specifications: "药品规格",
              product_name: "",
              supplier: '',//供应商
              number_unit: '',
              obj: {
                li: '5',
                list: [
                  {
                    value: '1',
                    label: '1年'
                  },
                  {
                    value: '2',
                    label: '2年'
                  },
                  {
                    value: '3',
                    label: '3年'
                  },
                  {
                    value: '4',
                    label: '4年'
                  },
                  {
                    value: '5',
                    label: '5年'
                  },
                ]
              },
              unitList: [],
              unit: '',
              piece_unit: ''
            }
          ],
        },
        count: 0,
        drug: {
          key: ''
        },
        drugList: [],
        defaultList: [],
        product_name: '',
        index: 'null',
        state: {
          drugs_management: {}
        },
        rules: {
          tableDataP_name: [{validator: checkSe, trigger: 'blur',}],
          tableDataN: [{validator: checkNu, trigger: 'blur'}],
          tableDataB: [{validator: checkbP, trigger: 'blur'}],
          tableDataP: [{validator: checkbP, trigger: 'blur'}],
        },
        booleBu: false,
        pickerOptions: {
          disabledDate(time) {
            //此条为设置禁止用户选择今天之前的日期，包含今天。
            return time.getTime() <= Date.now() - 8.64e7;
          }
        },
        inputList: [],
        timeDate:''


      }
    },
    watch: {
      formData: {
        handler() {
          if (this.formData.tableData.length > 0) {
            for (var i = 0; i < this.formData.tableData.length; i++) {
              if (Number(this.formData.tableData[i].product_id) > 0) {
                this.count++
              }
            }
          } else {
            this.count = 0
          }
        },
        deep: true
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.count > 0) {
        this.$confirm('有内容未保存, 是否确定离开此页面?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          next()
        }).catch(() => {
          next(false)
        });
      } else {
        next()
      }
    },
    created() {

    },
    mounted() {
      this.state = JSON.parse(this.$store.getters.systemSetting.dic_value)
      var date = new Date();
      var year = date.getFullYear()
      var year1 = date.getFullYear() + Number(this.formData.tableData[0].obj.li)
      var month = date.getMonth() + 1;
      month = (month < 10 ? '0' + month : month)
      var day = date.getDate();
      this.date = (year.toString() + '-' + month.toString() + '-' + day.toString())
      this.storage.date = (year.toString() + '-' + month.toString() + '-' + day.toString())
      this.timeDate = (year1.toString() + '-' + month.toString() + '-' + day.toString())
      this.formData.tableData[0].expire_time = this.timeDate
    },
    methods: {
      //入库日期事件
      onDate(val) {
        this.storage.date = val
      },
      //时间下拉
      onchange(index, val) {
        var date = new Date(this.storage.date);
        var year = date.getFullYear() + Number(val)
        var month = date.getMonth() + 1;
        month = (month < 10 ? '0' + month : month)
        var day = date.getDate();
        this.formData.tableData[index].expire_time = (year.toString() + '-' + month.toString() + '-' + day.toString())
      },
      //有效期
      onchangeEx(index, val) {
        this.formData.tableData[index].expire_time = val
        this.formData.tableData[index].obj.li = null
      },
      async querySearch(queryString, cb) {
        let reg = /^[a-zA-Z]+$/.test(queryString)
        if (reg === true) {
          queryString = queryString.toLowerCase()
        }
        let res = await getCentralList({prefix: queryString.replace(/(^\s*)|(\s*$)/g, ""), size: 10})
        if (res.code === 200 && res.data.self === true) {
          this.inputList = res.data.ElasticProduct || []
        } else {
          this.inputList = []
          this.formData.tableData[this.index].product_name = queryString
          this.product_name = queryString
          this.booleP_n = true
        }
        console.log(this.inputList.length, "--=-=-")
        var results = this.inputList;
        cb(results);
      },
      handleSelect(index, val) {
        console.log(index, val)
        getDefault(val.id).then(res => {
          if (res.code === 200 && res.data !== null) {
            this.defaultList = res.data
            if (this.defaultList !== null) {
              this.formData.tableData[index].piece_unit = this.defaultList.piece_unit
              this.formData.tableData[index].product_name = this.defaultList.product_name
              this.formData.tableData[index].specifications = this.defaultList.pack
              this.formData.tableData[index].production = this.defaultList.production
              this.formData.tableData[index].price = moneyFormat(Number(this.defaultList.price))
              this.formData.tableData[index].expire_time = this.timeDate || this.defaultList.expire_time
              this.formData.tableData[index].product_id = this.defaultList.id
              this.formData.tableData[index].unit = this.defaultList.number_unit
              this.formData.tableData[index].supplier = this.defaultList.supplier
              this.formData.tableData[index].split_piece = this.defaultList.split_piece
              this.formData.tableData[index].unitList = [this.defaultList.number_unit]
              if (this.defaultList.number_unit !== this.defaultList.piece_unit) {
                this.formData.tableData[index].unitList.push(this.defaultList.piece_unit)
              }
            }
          }
        })
      },
      onChangeInp(index, val) {
        this.formData.tableData[index].product_name = val
        if (val === '') {
          this.clearSl(index)
        }
      },
      //select获取焦点添加
      focusInp(index) {
        this.inputList = []
        this.index = index
        if (index === this.formData.tableData.length - 1) {
          this.addDrug()
        }
      },
      //select失去焦点
      blurIn(index) {
        if (this.inputList.length === 0 && this.formData.tableData[index].product_name === this.product_name) {
          this.formData.tableData[index].product_id = -1
        }
      },
      //select清除
      clearSl(index) {
        this.drugList = []
        this.count--
        this.formData.tableData[index].product_name = ''//名字
        this.formData.tableData[index].specifications = "药品规格"
        this.formData.tableData[index].production = "厂家" //厂家
        this.formData.tableData[index].number = null//数量
        this.formData.tableData[index].buy_price = null//进货价
        this.formData.tableData[index].price = null//处方价
        this.formData.tableData[index].batch_no = ""//批次号
        this.formData.tableData[index].expire_time = this.timeDate//有效期
        this.formData.tableData[index].product_id = 0
        this.formData.tableData[index].unit = ''
      },
      //入库数量焦点事件
      blurNn(index) {
        var reg = /(^[1-9]\d*$)/
        if (!this.formData.tableData[index].number || this.formData.tableData[index].number === '') {
        } else {
          if (!reg.test(this.formData.tableData[index].number)) {
            this.formData.tableData[index].number = ''
          } else {
            if (Number(this.formData.tableData[index].number) > 999999) {
              this.formData.tableData[index].number = ''
            }
          }
        }

      },
      //单位
      onChangeUn(index, val) {
        this.formData.tableData[index].unit = val
      },
      //进货价焦点事件
      blurBu(index) {
        var reg = /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/
        if (!this.formData.tableData[index].buy_price || this.formData.tableData[index].buy_price === '') {
          this.formData.tableData[index].buy_price = moneyFormat(0)
        } else {
          if (reg.test(this.formData.tableData[index].buy_price)) {
            this.formData.tableData[index].buy_price = moneyFormat(this.formData.tableData[index].buy_price)
          } else {
            this.formData.tableData[index].buy_price = moneyFormat(0)
          }
        }
      },
      //处方价焦点事件
      blurPr(index) {
        var reg = /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/
        if (!this.formData.tableData[index].price || this.formData.tableData[index].price === '') {
          this.formData.tableData[index].price = moneyFormat(0)
        } else {
          if (reg.test(this.formData.tableData[index].price)) {
            this.formData.tableData[index].price = moneyFormat(this.formData.tableData[index].price)
          } else {
            this.formData.tableData[index].price = moneyFormat(0)
          }
        }
      },
      //保存
      save() {
        for (var i = 0; i < this.formData.tableData.length; i++) {
          if (this.formData.tableData[i].product_name.split(" ").join("").length !== 0) {
            if (this.formData.tableData[i].product_name !== '' || this.formData.tableData[i].product_name !== null) {
              this.$confirm('是否确定保存？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(_ => {
                this.determine()
              }).catch(_ => {
              })
            }
          }

        }
      },
      //保存确定
      determine() {
        var arr = [], data = [], boole = true, boolList = false;
        for (var i = 0; i < this.formData.tableData.length; i++) {
          if (this.formData.tableData[i].product_name.split(" ").join("").length !== 0) {
            if (this.formData.tableData[i].product_name !== '' || this.formData.tableData[i].product_name !== null) {
              if (this.formData.tableData[i].number === '' || this.formData.tableData[i].number === null || this.formData.tableData[i].number === 0) {
                let str = "numIn" + i
                this.$nextTick(_ => {
                  this.$refs[str].focus()
                  this.$refs[str].blur()
                })
                boole = false
              } else {
                if (this.formData.tableData[i].product_id > 0) {
                  arr.push(i)
                  boolList = true
                }
              }
            }
          }
        }
        if (boole && boolList) {
          arr.forEach(item => {
            data.push(
              {
                product_id: this.formData.tableData[item].product_id,
                buy_price: Number(this.formData.tableData[item].buy_price),
                price: Number(this.formData.tableData[item].price),
                number: Number(this.formData.tableData[item].number),
                batch_no: this.formData.tableData[item].batch_no,
                expire_time: this.formData.tableData[item].expire_time,
                supplier: this.storage.manufacturers || this.formData.tableData[item].supplier,
                unit: this.formData.tableData[item].unit
              }
            )
          })
          this.booleBu = true
          addStoragerList({data}).then(res => {
            if (res.code === 200) {
              this.count = 0
              // this.dialogVisible = false
              this.$router.push('/drugsManagement/pushWarehouse/storageLog')
            } else {
              this.booleBu = false
            }
          })
        }

      },
      //入库日志
      tosSorageLog() {
        this.$router.push('/drugsManagement/pushWarehouse/storageLog')
      },
      //添加药品
      addDrug() {
        this.formData.tableData.push(
          {
            product_id: 0,//id
            buy_price: null,//进货价
            price: null,//处方价
            number: null,//数量
            batch_no: "",//批次号
            expire_time: this.timeDate,//有效期
            production: "厂家",//厂家
            specifications: "药品规格",
            product_name: "",
            supplier: '',
            number_unit: '',
            obj: {
              li: '5',
              list: [
                {
                  value: '1',
                  label: '1年'
                },
                {
                  value: '2',
                  label: '2年'
                },
                {
                  value: '3',
                  label: '3年'
                },
                {
                  value: '4',
                  label: '4年'
                },
                {
                  value: '5',
                  label: '5年'
                },
              ]
            },
            unitList: [],
            unit: '',
            piece_unit: ''
          }
        )
      },
      //删除药品
      deleteDrug(index) {
        for (let i = 0; i < this.formData.tableData.length; i++) {
          if (i === index) {
            this.$refs.formData.fields.map(j => {
              let str = `tableData.${i}.number`
              let er = `tableData.${i}.product_name`
              if (j.prop === str) {
                j.clearValidate()
              } else if (j.prop === er) {
                j.clearValidate()
              }
            })
            this.formData.tableData.splice(i, 1)
          }
        }

      }
    }
  }
</script>
<style lang="scss" scoped>
  @import "@/assets/scss/drugsManagement/pushWarehouse.scss";

  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: rgba(0, 0, 0, 0) !important;
  }

</style>
